import { ref } from 'vue';
import parseLyric from '@/utils/parseLyric';
import { useSongURL, useSongLyric } from '@/api/music';
import type { IPlayList, IMusic } from './type';

const setup = () => {
	// 播放列表
	const playList = ref<IPlayList[]>([]);
	// 播放音乐消息
	const playResult = ref<IPlayList>();
	// 播放状态
	const playState = ref(false);
	// 播放音乐
	const music = ref<IMusic>();
	// 是否显示歌词
	const lyricState = ref(true);

	// 获取播放音乐
	const getPlayMusic = async () => {
		if (!playResult.value?.id) return;
		// 获取url
		const urlResult = await useSongURL(playResult.value.id);
		const { id, url } = urlResult.data[0];
		// 获取歌词
		const lyricResult = await useSongLyric(playResult.value.id);
		const { lyric } = lyricResult.lrc;
		music.value = {
			id,
			url,
			time: 0,
			lyric: parseLyric(lyric),
		};
	};

	// 上一曲
	const setPreviousSong = () => {
		// 获取播放音乐在数组中下标
		let songIndex = playList.value.findIndex(obj => obj.id === playResult.value?.id);
		// 如果是最后一首
		if (songIndex === 0) songIndex = playList.value.length;
		// 设置下一曲
		playResult.value = playList.value[songIndex - 1];
		// 若是播放状态 调用请求歌词接口
		if (playState.value) getPlayMusic();
	};

	// 开启音乐
	const playMusic = () => {
		playState.value = true;
		getPlayMusic();
	};

	// 暂停音乐
	const pauseMusic = () => {
		playState.value = false;
	};

	// 下一曲
	const setNextSong = () => {
		// 获取播放音乐在数组中下标
		let songIndex = playList.value.findIndex(obj => obj.id === playResult.value?.id);
		// 如果是最后一首
		if (songIndex === playList.value.length - 1) songIndex = -1;
		// 设置下一曲
		playResult.value = playList.value[songIndex + 1];
		// 若是播放状态 调用请求歌词接口
		if (playState.value) getPlayMusic();
	};

	return {
		playList,
		playResult,
		playState,
		music,
		lyricState,
		getPlayMusic,
		setPreviousSong,
		playMusic,
		pauseMusic,
		setNextSong,
	};
};

export default setup;
